package com.lizhenhua.api.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lizhenhua.api.feignClient.UserCheckFeignClient;
import com.lizhenhua.api.service.UserLoginService;
import com.lizhenhua.fmmall.beans.Users;
import com.lizhenhua.fmmall.utils.MD5Utils;
import com.lizhenhua.fmmall.vo.ResStatus;
import com.lizhenhua.fmmall.vo.ResultVo;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private UserCheckFeignClient userCheckFeignClient;

    @Autowired
    private ObjectMapper o;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResultVo checkLogin(String userName, String pwd) {
        // 1.调用api-user-check服务 查询用户名信息
        Users users = userCheckFeignClient.checkUser(userName);

        //2. 进行用户信息的校验
        if (users == null) {
            return new ResultVo(ResStatus.NO, "login...fail", null);
        } else {
            // 对输入的密码进行加密
            String password = MD5Utils.md5(pwd);
            // 使用加密后的密码 和 user中的密码进行匹配
            if (users.getPassword().equals(password)) {
                // token方法
//                String token = Base64Utils.encode(userName+123456);
                // 使用jwt 生成token 工厂模式
                JwtBuilder builder = Jwts.builder();
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("key1", "value1");
                hashMap.put("key2", "value2");
                String token = builder.setSubject(userName)
                        .setIssuedAt(new Date()) //创建token生成的时间
                        .setId(users.getUserId() + "") //  id 为Users的id
                        .setClaims(hashMap)  // map中可以存放用户的权限信息
                        .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000))//设置过期时间
                        .signWith(SignatureAlgorithm.HS256, "aaa123")//设置加密方式 和加密密码
                        .compact();// .compact() 会返回一个字符串

                //当用户登录成功之后 以token为key 将信息保存到redis中
                try {
                    String userInfo = o.writeValueAsString(users);
                    System.out.println(userInfo);
                    stringRedisTemplate.boundValueOps(token).set(userInfo, 20, TimeUnit.MINUTES);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }


                return new ResultVo(ResStatus.OK, token, users);
            } else {
                return new ResultVo(ResStatus.NO, "登陆失败,密码错误", null);
            }
        }
    }
}
